<template>
  <div>
    <div class="professions-container">
      <!-- 左侧培养计划列表 -->
      <div class="left-content">      <!-- 添加培养计划按钮 -->
      <div class="add-button-container">
        <el-button type="primary" icon="el-icon-plus" @click="showAddForm" v-hasPermi="['degree:professions:add']">添加专业</el-button>
      </div>
        
        <!-- 培养计划列表表格 -->
        <el-table 
          v-loading="loading" 
          :data="professionsList" 
          border
          stripe
          max-height="500"
          empty-text="暂无培养计划数据，请先添加培养计划信息">
          <el-table-column type="index" width="50" label="#" align="center" />
          <el-table-column label="院系名称" align="center" prop="departmentName" />
          <el-table-column label="专业名称" align="center" prop="name" width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="授课语言" align="center" prop="languageId" width="150" show-overflow-tooltip>
           <template slot-scope="scope">
    <span v-if="scope.row.languages">
      <span v-for="(lang, idx) in scope.row.languages.split(',')" :key="lang">
        {{ getDictLabel('teachlanguage', lang) }}<span v-if="idx < scope.row.languages.split(',').length - 1">, </span>
      </span>
    </span>
    <span v-else>-</span>
  </template>
          </el-table-column>
          <el-table-column label="学费" align="center" prop="tuition" width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.tuition != null && scope.row.tuition !== ''">{{ scope.row.tuition }}元</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="开学时间" align="center" prop="openingDateId" width="150" show-overflow-tooltip>
            <template slot-scope="scope">
    <span v-if="scope.row.openingDates">
      <span v-for="(date, idx) in scope.row.openingDates.split(',')" :key="date">
        {{ getDictLabel('opening_dates', date) }}<span v-if="idx < scope.row.openingDates.split(',').length - 1">, </span>
      </span>
    </span>
    <span v-else>-</span>
  </template>
          </el-table-column>
          <el-table-column label="学位" align="center" prop="degree" width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ getDictLabel('degree_type', scope.row.degree) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="培养计划简介" align="center" prop="intro" width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.intro">{{ scope.row.intro }}</span>
              <span v-else style="color: #999">-</span>
            </template>
          </el-table-column>
                <el-table-column label="二级标题" align="center" prop="subTitle" width="130" show-overflow-tooltip />
      <el-table-column label="学制" align="center" prop="years" width="130" show-overflow-tooltip />
       <el-table-column label="学历" align="center" prop="requestDegree" width="130" show-overflow-tooltip />
      <el-table-column label="年龄" align="center" prop="requestAge" width="130" show-overflow-tooltip />
      <el-table-column label="语言" align="center" prop="requestLanguage" width="130" show-overflow-tooltip />
      <el-table-column label="成绩" align="center" prop="requestScore" width="130" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="250" fixed="right">
            <template slot-scope="scope">
              <div class="operation-buttons">
                <el-button 
                  size="mini" 
                  type="primary" 
                  @click="handleUpdate(scope.row)" 
                  v-hasPermi="['degree:professions:edit']">编辑</el-button>
                <el-button 
                  size="mini" 
                  type="success" 
                  @click="openCoursesDialog(scope.row)" 
                  v-hasPermi="['degree:classes:list']">课程编辑</el-button>
                <el-button 
                  size="mini" 
                  type="danger" 
                  @click="handleDelete(scope.row, scope.$index)" 
                  v-hasPermi="['degree:professions:remove']">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

    </div>
    </div>

    <!-- 全屏右侧表单抽屉 -->
    <div class="profession-drawer-overlay" v-if="showForm" @click="hideForm">
      <div class="profession-drawer" @click.stop>
        <div class="drawer-header">
          <h3>{{ form.id ? '编辑专业' : '添加专业' }}</h3>
          <el-button type="text" icon="el-icon-close" @click="hideForm" class="close-btn"></el-button>
        </div>
        
        <div class="drawer-content">
          <el-form :model="form" ref="form" :rules="rules" label-width="120px" class="profession-form">
            <el-row :gutter="24">
               <el-form-item label="选择院系" prop="departmentId" class="required-field">
                  <el-select 
                    v-model="form.departmentId" 
                    placeholder="请选择院系" 
                    style="width: 100%" 
                    clearable
                    :filterable="false">
                    <el-option
                      v-for="dept in departmentList"
                      :key="dept.id"
                      :label="dept.departName"
                      :value="Number(dept.id)"
                    />
                  </el-select>
                </el-form-item>
              <el-col :span="24">
                <el-form-item label="专业名称" prop="name" class="required-field">
                  <el-input v-model="form.name" placeholder="请输入专业名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="教学语言" prop="languageId" class="required-field">
                   <el-checkbox-group v-model="languageArray" style="width: 100%">
                      <el-checkbox 
                        v-for="dict in teachLanguageOptions" 
                        :key="dict.value" 
                        :label="dict.value">
                        {{ dict.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="学费" prop="tuition" class="required-field">
                  <el-input 
                    v-model="form.tuition" 
                    placeholder="请输入学费"
                    clearable>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="开学时间" class="required-field">
                      <el-checkbox-group v-model="openingDateArray" style="width: 100%">
                        <el-checkbox label="1">春季开学</el-checkbox>
                        <el-checkbox label="2">秋季开学</el-checkbox>
                      </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="学位" prop="degree" class="required-field">
                  <el-select 
                    v-model="form.degree" 
                    placeholder="请选择学位" 
                    style="width: 100%" 
                    clearable
                    :filterable="false">
                    <el-option
                      v-for="dict in degreeTypeOptions"
                      :key="dict.value"
                      :label="dict.label"
                      :value="Number(dict.value)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
           <el-col :span="24">
  <!-- <el-form-item label="二级标题" prop="subTitle" class="required-field">
    <el-input
      v-model="form.subTitle"
      placeholder="请输入二级标题（最多26个字111）"
      clearable
      maxlength="26"
      show-word-limit
    />
  </el-form-item> -->
</el-col>
            </el-row>
             <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="学制" prop="years" class="required-field">
                  <el-input v-model="form.years" :value="form.years" placeholder="请输入学制" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <!--前置要求 标题-->
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="前置-学历" prop="requestDegree" class="required-field">
                  <el-input v-model="form.requestDegree" placeholder="请输入学历" clearable />
                </el-form-item>
              </el-col>
            </el-row>
             <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="前置-年龄" prop="requestAge" class="required-field">
                  <el-input v-model="form.requestAge" placeholder="请输入年龄" clearable />
                </el-form-item>
              </el-col>
            </el-row>
             <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="前置-语言" prop="requestLanguage" class="required-field">
                  <el-input v-model="form.requestLanguage" placeholder="请输入语言" clearable />
                </el-form-item>
              </el-col>
            </el-row>
             <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="前置-成绩" prop="requestScore" class="required-field">
                  <el-input v-model="form.requestScore" placeholder="请输入成绩" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="前置-其他" prop="requestOthers" class="required-field">
                  <el-input v-model="form.requestOthers" placeholder="请输入其他要求" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="专业简介" prop="intro">
                  <el-input 
                    v-model="form.intro" 
                    type="textarea" 
                    :rows="3" 
                    placeholder="请输入专业简介（小程序最多能显示500个文字，其余用省略号表示）" 
                    maxlength="500"
                    show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="前置培养要求" prop="requirements">
                  <el-input 
                    v-model="form.requirements" 
                    type="textarea" 
                    :rows="3" 
                    placeholder="请输入前置培养要求" 
                    maxlength="500"
                    show-word-limit />
                </el-form-item>
              </el-col>
            </el-row> -->

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="培养计划优势" prop="eduPlanAdvantage">
                  <el-button size="mini" type="primary" @click="openIntroEditor">编辑简介</el-button>
                </el-form-item>
              </el-col>
            </el-row>

            
  
          </el-form>
        </div>

        <div class="drawer-footer">
          <el-button type="primary" @click="submitForm(false)" :loading="saving">
            {{ form.id ? '更新' : '保存' }}
          </el-button>
          <el-button type="primary" @click="submitForm(true)" :loading="saving">
           继续添加
          </el-button>
          <el-button @click="handleCancel">
            {{ form.id ? '取消编辑' : '取消' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 课程编辑右侧抽屉 -->
    <div class="courses-drawer-overlay" v-if="showCoursesDialog" @click="closeCoursesDialog">
      <div class="courses-drawer" @click.stop>
        <div class="drawer-header">
          <h3>{{ currentProfession ? `"${currentProfession.name}" 的课程管理` : '课程管理' }}</h3>
          <el-button type="text" icon="el-icon-close" @click="closeCoursesDialog" class="close-btn"></el-button>
        </div>
        
        <div class="drawer-content">
          <!-- 课程表单区域 -->
          <el-form :model="courseForm" ref="courseForm" :rules="courseRules" label-width="120px" class="course-form">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="课程名称" prop="name" class="required-field">
                  <el-input v-model="courseForm.name" placeholder="请输入课程名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="排序" prop="orderNum">
                  <el-input-number 
                    v-model="courseForm.orderNum" 
                    :min="0" 
                    :max="999" 
                    placeholder="请输入排序"
                    style="width: 100%"
                    controls-position="right" />
                </el-form-item>
              </el-col>
            </el-row>
            
<!-- 添加课程按钮区域 - 移动到排序下面并向右偏移50px -->
<div style="text-align: center; margin-top: 20px; margin-bottom: 20px; transform: translateX(50px);">
  <el-button type="primary" @click="saveCourse" v-if="!isEditingCourse" v-hasPermi="['degree:classes:add']">添加课程</el-button>
  <el-button type="success" @click="updateCourse" v-if="isEditingCourse" v-hasPermi="['degree:classes:edit']">更新课程</el-button>
  <el-button @click="resetCourseForm" v-if="isEditingCourse">取消编辑</el-button>
</div>
          </el-form>

          <!-- 课程列表 -->
          <div class="courses-list" style="margin-top: 24px;">
            <h4 style="margin-bottom: 16px; color: #303133; font-size: 16px; font-weight: 600;">课程列表</h4>
            <el-table :data="coursesList" v-loading="coursesLoading" border style="width: 100%" max-height="400" empty-text="暂无课程数据，请先添加课程信息">
              <el-table-column prop="name" label="课程名称" align="center" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-if="scope.row.name">{{ scope.row.name }}</span>
                  <span v-else style="color: #999">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="orderNum" label="排序" align="center" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.orderNum || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180" fixed="right">
                <template slot-scope="scope">
                  <div class="operation-buttons">
                    <el-button 
                      size="mini" 
                      type="primary" 
                      @click="editCourse(scope.row)" 
                      v-hasPermi="['degree:classes:edit']">编辑</el-button>
                    <el-button 
                      size="mini" 
                      type="danger" 
                      @click="deleteCourse(scope.row)" 
                      v-hasPermi="['degree:classes:remove']">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="data-info" style="margin-top: 10px; padding: 10px; background: #f5f7fa; border-radius: 4px; font-size: 14px; color: #666;">
              <span>共找到 {{ coursesList.length }} 条课程记录（当前院校：{{ schoolId }}，当前培养计划：{{ currentProfession ? currentProfession.id : '-' }}）</span>
            </div>
          </div>
        </div>

        <!-- 抽屉底部按钮区域 -->
        <div class="drawer-footer">
          <el-button @click="closeCoursesDialog">关闭</el-button>
        </div>
      </div>
    </div>
       <!--弹窗编辑器-->
  <el-dialog
      title="编辑院校简介"
      :visible.sync="introEditorVisible"
      width="1000px"
      append-to-body
    >
      <MiniEditor
        v-model="introContent"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="introEditorVisible = false">取消</el-button>
        <el-button type="primary" @click="saveIntro">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listProfessions, getProfessions, addProfessions, updateProfessions, delProfessions } from "@/api/degree/professions"
import { listClasses, getClasses, addClasses, updateClasses, delClasses } from "@/api/degree/classes"
import { listDepartment} from "@/api/degree/department"
import MiniEditor from "@/views/degree/schools/components/mini_editor.vue"
export default {
  components: {
    MiniEditor
  },
  name: "Professions",
  dicts: ['teachlanguage', 'edu_plan', 'degree_type'],
  props: {
    schoolId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loading: false,
      saving: false,
      showForm: false, // 控制右侧表单显示/隐藏
      form: {
        id: null,
        schoolId: 0,
        name: '',                    // 培养计划名称
        languageId: '',             // 教学语言
        tuition: '',                // 学费
        openingDateId: '',          // 开学时间
        degree: '',                 // 学位
        intro: '',                  // 培养计划简介
        requirements: '',           // 前置培养要求
        eduPlanAdvantage: '',        // 培养计划优势
        departmentId:0,
        requestDegree:'',
        requestAge:'16',
        requestLanguage:'中文',
        requestScore:'',
        requestOthers:'',
        years:'1年学制',
        subTitle:'',
        languages:'',
        openingDates:''
      },
      openingDateArray:[],
      languageArray:[],
      rules: {
        name: [
          { required: true, message: '请输入培养计划名称', trigger: 'blur' }
        ],
        tuition: [
          { required: true, message: '请输入学费', trigger: 'blur' }
        ],
        degree: [
          { required: true, message: '请选择学位', trigger: 'change' }
        ],
         departmentId: [
          { required: true, message: '请选择院系', trigger: 'change' }
        ]
      },
      professionsList: [],
      
      // 课程编辑相关数据
      showCoursesDialog: false,
      currentProfession: null,
      coursesLoading: false,
      coursesList: [],
      courseForm: {
        id: null,
        schoolId: 0,
        professionId: null,
        name: '',
        orderNum: 0
      },
      courseRules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ]
      },
      isEditingCourse: false,
      editingCourseId: null,
      departmentList:[],
      introEditorVisible: false,
      introContent: '',
   
    }
  },
  computed: {
    // 计算属性确保字典数据能正确访问
    teachLanguageOptions() {
      const dicts = this.dict.type.teachlanguage
      if (!dicts) return []
      return Array.isArray(dicts) ? dicts : Object.values(dicts)
    },
    eduPlanOptions() {
      const dicts = this.dict.type.edu_plan
      if (!dicts) return []
      return Array.isArray(dicts) ? dicts : Object.values(dicts)
    },
    degreeTypeOptions() {
      const dicts = this.dict.type.degree_type
      if (!dicts) return []
      return Array.isArray(dicts) ? dicts : Object.values(dicts)
    }
  },
  watch: {
    schoolId: {
      handler(newVal, oldVal) {
        this.getList()
        this.getDepartmentList()
      },
      immediate: true
    }
  },
  mounted() {
    this.checkAndLoadDicts()
  },
  methods: {
      openIntroEditor() {
          console.log('打开简介编辑器，当前简介内容:', this.form.intro)
          this.introEditorVisible = true
          // 可根据实际需求初始化内容
          console.log(" this.introContent"+ this.introContent)
          this.introContent = this.form.eduPlanAdvantage || ''
        },
      saveIntro() {
        console.log('保存简介内容:', this.introContent)
        // 保存内容到表单
        this.form.eduPlanAdvantage = this.introContent
        this.introEditorVisible = false
      
       // this.$message.success('简介已保存')

      },
    getDepartmentList() {
      const queryParamsDept = {
        schoolId: this.schoolId, // 添加院校ID过滤
      }
      
      this.loading = true
      listDepartment(queryParamsDept).then(response => {
        this.departmentList = response.rows
        this.loading = false
      })
    },
    
    /** 显示添加表单 */
    showAddForm() {
      this.getDepartmentList();
      this.handleReset() // 重置表单数据
      this.showForm = true
    },

    /** 隐藏表单 */
    hideForm() {
      this.showForm = false
      this.handleReset() // 隐藏时重置表单
    },

    /** 查询培养计划列表 */
    getList() {
      this.loading = true
      
      const queryParams = {
        pageNum: 1,
        pageSize: 1000,
        schoolId: this.schoolId, // 添加院校ID过滤
        orderByColumn: 'school_id',
        isAsc: 'desc'
      }
      
      listProfessions(queryParams).then(response => {
        this.loading = false
        const rawData = response.rows || response.data || []
        this.professionsList = this.validateAndFixData(rawData, 'profession')
      }).catch(error => {
        this.loading = false
        this.professionsList = []
        
        // 处理字符串类型的错误
        if (typeof error === 'string') {
          if (error === 'error') {
            this.$message.error("获取培养计划列表失败：后端接口异常")
          } else {
            this.$message.error("获取培养计划列表失败：" + error)
          }
          return
        }
        
        // 检查是否是权限相关错误
        if (error?.response?.status === 403 || error?.message?.includes('权限')) {
          this.$message.error("获取培养计划列表失败：没有访问权限")
        } else if (error?.response?.status === 401) {
          this.$message.error("获取培养计划列表失败：身份认证已过期，请重新登录")
        } else if (!error?.message && !error?.status) {
          this.$message.error("获取培养计划列表失败：网络异常或请求被拦截")
        } else {
          this.$message.error("获取培养计划列表失败：" + (error?.msg || error?.message || '未知错误'))
        }
      })
    },

    /** 数据验证和修正 */
    validateAndFixData(dataList, type = 'profession') {
      if (!Array.isArray(dataList)) {
        return []
      }
      
      return dataList
        .filter(item => !this.schoolId || item.schoolId === this.schoolId) // 过滤当前院校数据
        .map((item, index) => {
          // 基本字段验证
          const validatedItem = {
            ...item,
            id: item.id || null,
            schoolId: item.schoolId || this.schoolId
          }
          
          if (type === 'profession') {
            // 培养计划数据特定验证
            validatedItem.name = item.name || ''
            validatedItem.languageId = item.languageId || ''
             validatedItem.departmentId = item.departmentId || ''
            validatedItem.tuition = item.tuition || ''
            validatedItem.openingDateId = item.openingDateId || ''
            validatedItem.degree = item.degree || ''
            validatedItem.intro = item.intro || ''
            validatedItem.requirements = item.requirements || ''
            validatedItem.eduPlanAdvantage = item.eduPlanAdvantage || ''
          }
          
          return validatedItem
        })
    },

    /** 提交表单 */
    //如果next = true 则点击后继续添加
    submitForm(next) {
      // 先检查字典数据是否就绪
      // if (!this.isDictDataReady()) {
      //   this.$message.warning('字典数据尚未加载完成，请稍后再试')
      //   return
      // }
      
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保数据完整性
          const formData = { ...this.form }
          formData.schoolId = this.schoolId || formData.schoolId
          
          // 确保 id 字段是数字类型或 null
          if (formData.id !== null && formData.id !== undefined && formData.id !== '') {
            const idNum = Number(formData.id)
            formData.id = isNaN(idNum) ? null : idNum
          }
          
          // 验证必填字段
          if (!formData.name || formData.name.trim() === '') {
            this.$message.error('请输入培养计划名称')
            return
          }
          
           if (formData.departmentId === null || formData.departmentId === undefined || formData.departmentId === '') {
            this.$message.error('请选择院系')
            return
          }
          
          if (!formData.tuition || formData.tuition.trim() === '') {
            this.$message.error('请输入学费')
            return
          }
          
          
          if (formData.degree === null || formData.degree === undefined || formData.degree === '') {
            this.$message.error('请选择学位')
            return
          }
          
          // 确保字符串字段类型正确
          formData.tuition = String(formData.tuition || '').trim()
          if (formData.degree !== '' && formData.degree !== null && formData.degree !== undefined) {
            const degreeNum = Number(formData.degree)
            if (isNaN(degreeNum) || degreeNum < 0) {
              this.$message.error('学位选择无效，请重新选择')
              return
            }
            formData.degree = degreeNum
          } else {
            this.$message.error('请选择学位')
            return
          }
          
          // 修复 schoolId 问题：确保 schoolId 是有效的数字
          if (this.schoolId && this.schoolId > 0) {
            formData.schoolId = Number(this.schoolId)
          } else {
            this.$message.error('院校信息无效，请先保存院校基本信息')
            return
          }
          
          // 处理 orderNum
          if (formData.orderNum && formData.orderNum !== '') {
            const orderNumVal = parseInt(formData.orderNum)
            formData.orderNum = isNaN(orderNumVal) ? null : orderNumVal
          } else {
            formData.orderNum = null
          }
          if(this.languageArray.length>0){
            formData.languages=this.languageArray.join(',') 
          }
          if(this.openingDateArray.length>0){
            formData.openingDates=this.openingDateArray.join(',') 
          }


          // 清理数据，确保所有字段都是基本数据类型
          const cleanFormData = {
            id: formData.id,
            name: String(formData.name || ''),
            // languageId: Number(formData.languageId),
            departmentId: Number(formData.departmentId),
            tuition: String(formData.tuition || ''),
            // openingDateId: Number(formData.openingDateId),
            schoolId: Number(formData.schoolId),
            degree: Number(formData.degree),
            intro: String(formData.intro || ''),
            requirements: String(formData.requirements || ''),
            eduPlanAdvantage: String(formData.eduPlanAdvantage || ''),
            requestDegree: String(formData.requestDegree || ''),
            requestAge: String(formData.requestAge || ''),
            requestLanguage: String(formData.requestLanguage || ''),
            requestScore: String(formData.requestScore || ''),
            years: String(formData.years || ''),
            subTitle: String(formData.subTitle || ''),
            languages: String(formData.languages || ''),
            openingDates: String(formData.openingDates || '')
          }
          
          // 最终数据验证（对清理后的数据进行验证）
          if (!Number.isInteger(cleanFormData.schoolId) || cleanFormData.schoolId <= 0) {
            this.$message.error('院校ID必须是有效的正整数')
            return
          }
          
          // if (!Number.isInteger(cleanFormData.languageId) || cleanFormData.languageId < 0) {
          //   this.$message.error('教学语言ID必须是有效的非负整数')
          //   return
          // }
          
          // if (!Number.isInteger(cleanFormData.openingDateId) || cleanFormData.openingDateId < 0) {
          //   this.$message.error('开学时间ID必须是有效的非负整数')
          //   return
          // }
          
          if (!Number.isInteger(cleanFormData.degree) || cleanFormData.degree < 0) {
            this.$message.error('学位ID必须是有效的非负整数')
            return
          }

          // 直接保存到数据库
          if (formData.id && !String(formData.id).startsWith('temp_')) {
            // 更新培养计划
            updateProfessions(cleanFormData).then(response => {
              this.$message.success("培养计划修改成功")
              this.getList() // 重新获取列表
              this.handleReset()
              this.hideForm() // 保存成功后隐藏表单
            }).catch(error => {
              this.$message.error("培养计划修改失败：" + (error.msg || error.message || '未知错误'))
            })
          } else {
            // 新增培养计划
            const { id, ...addData } = cleanFormData // 移除临时ID
            addProfessions(addData).then(response => {
              this.$message.success("培养计划新增成功")
              this.getList() // 重新获取列表
              this.handleReset()
              if (!next) {
                this.hideForm() // 保存成功后隐藏表单
              }else{
                this.form.departmentId = cleanFormData.departmentId
                this.form.schoolId = cleanFormData.schoolId
              }
            
            }).catch(error => {
              this.$message.error("培养计划新增失败：" + (error.msg || error.message || '未知错误'))
            })
          }
          
        } else {
          this.$message.error('请检查表单数据')
        }
      })
    },

    /** 检查字典数据是否就绪 */
    isDictDataReady() {
      const requiredDicts = ['teachlanguage', 'edu_plan', 'degree_type']
      
      for (const dictKey of requiredDicts) {
        const dictData = this.dict.type[dictKey]
        if (!dictData || !Array.isArray(dictData) || dictData.length === 0) {
          return false
        }
      }
      
      return true
    },

    /** 取消操作 */
    handleCancel() {
      this.hideForm()
    },

    /** 重置表单 */
    handleReset() {
      this.form = {
        id: null,
        schoolId: this.schoolId,
        name: '',
        languageId: null,
        departmentId: null,
        tuition: '',
        openingDateId: null,
        degree: null,
        intro: '',
        requirements: '',
        eduPlanAdvantage: '',
        requestDegree:'',
        requestAge:'',
        requestLanguage:'',
        requestScore:'',
        years:'',
        subTitle:'',
        languages:'',
        openingDates:''
      }
      this.languageArray=[]
      this.openingDateArray=[]
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },

    /** 编辑培养计划 */
    handleUpdate(row) {
      // if (!this.isDictDataReady()) {
      //   this.$message.warning('字典数据尚未加载完成，请稍后再试')
      //   return
      // }
      
      this.form = {
        ...row,
        languageId: this.ensureNumericValue(row.languageId),
        openingDateId: this.ensureNumericValue(row.openingDateId),
        degree: this.ensureNumericValue(row.degree),
        requirements: row.requirements || '',
        eduPlanAdvantage: row.eduPlanAdvantage || '',
        requestDegree: row.requestDegree || '',
        requestAge: row.requestAge || '',
        requestLanguage: row.requestLanguage || '',
        requestScore: row.requestScore || '',
        years: row.years || '',
        subTitle: row.subTitle || '',
        languages: row.languages || '',
        openingDates: row.openingDates || ''
      }
      if(row.languages){
        this.languageArray=row.languages.split(',')
      }else{
        this.languageArray=[]
      }
      if(row.openingDates){
        this.openingDateArray=row.openingDates.split(',')
      }else{
        this.openingDateArray=[]
      }

      
      this.validateDictValues()
      this.showForm = true
    },

    /** 验证字典值是否有效 */
    validateDictValues() {
      // 这里可以添加验证逻辑，目前保持简化
    },

    /** 确保值为数字类型，用于字典选择器 */
    ensureNumericValue(value) {
      if (value === null || value === undefined || value === '') {
        return ''
      }
      
      const numValue = parseInt(value)
      
      if (isNaN(numValue)) {
        return ''
      }
      
      return numValue
    },

    /** 删除培养计划 */
    handleDelete(row, index) {
      this.$confirm('确认删除该培养计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.isTemp || String(row.id).startsWith('temp_')) {
          if (index !== undefined) {
            this.professionsList.splice(index, 1)
          } else {
            const findIndex = this.professionsList.findIndex(item => item.id === row.id)
            if (findIndex > -1) {
              this.professionsList.splice(findIndex, 1)
            }
          }
          this.$message.success("培养计划已删除")
        } else {
          delProfessions(row.id).then(response => {
            this.$message.success("培养计划删除成功")
            this.getList()
          }).catch(error => {
            this.$message.error("培养计划删除失败：" + (error.msg || error.message || '未知错误'))
          })
        }
      }).catch(() => {})
    },

    /** 获取字典标签 - 增强版 */
    getDictLabel(dictType, value) {
      if (value === null || value === undefined || value === '') {
        return '-'
      }
      
      let dictOptions = []
      if (dictType === 'teachlanguage') {
        dictOptions = this.teachLanguageOptions
      } else if (dictType === 'edu_plan') {
        dictOptions = this.eduPlanOptions
      } else if (dictType === 'degree_type') {
        dictOptions = this.degreeTypeOptions
      }else if(dictType === 'opening_dates'){
        dictOptions = [
          { value: '1', label: '春季开学' },
          { value: '2', label: '秋季开学' }
        ]
      } else {
        return `未知(${value})`
      }
      
      if (!dictOptions || !Array.isArray(dictOptions) || dictOptions.length === 0) {
        return `未知(${value})`
      }
      
      let matchedOption = null
      
      // 精确匹配
      matchedOption = dictOptions.find(option => option.value === value)
      
      // 类型转换匹配
      if (!matchedOption) {
        matchedOption = dictOptions.find(option => {
          return String(option.value) === String(value) ||
                 parseInt(option.value) === parseInt(value) ||
                 parseFloat(option.value) === parseFloat(value)
        })
      }
      
      // 宽松匹配
      if (!matchedOption) {
        matchedOption = dictOptions.find(option => {
          return String(option.value).trim() === String(value).trim()
        })
      }
      
      if (matchedOption) {
        return matchedOption.label
      } else {
        return `未知(${value})`
      }
    },

    /** 获取并检查字典数据 */
    async checkAndLoadDicts() {
      await this.$nextTick()
      
      const dicts = ['teachlanguage', 'edu_plan', 'degree_type']
      const incompleteDict = dicts.find(dictKey => {
        const dictData = this.dict.type[dictKey]
        return !dictData || !Array.isArray(dictData) || dictData.length === 0
      })
      
      if (incompleteDict) {
        // 如果需要，可以在这里添加重新获取字典的逻辑
      }
    },

    /** 检查是否有未保存的数据 - 为主页面提供 */
    hasUnsavedData() {
      return false
    },

    /** 保存当前数据 - 为主页面提供 */
    async saveCurrentData() {
      return Promise.resolve(true)
    },

    /** 获取当前组件状态 - 为主页面提供 */
    getComponentStatus() {
      return {
        hasData: this.professionsList.length > 0,
        schoolId: this.schoolId,
        dataCount: this.professionsList.length
      }
    },

    // ========== 课程编辑相关方法 ==========

    /** 打开课程编辑弹出框 */
    openCoursesDialog(profession) {
      this.currentProfession = profession
      this.resetCourseForm()
      this.showCoursesDialog = true
      this.getCoursesList()
    },

    /** 关闭课程编辑弹出框 */
    closeCoursesDialog() {
      this.showCoursesDialog = false
      this.currentProfession = null
      this.resetCourseForm()
      this.coursesList = []
    },

    /** 重置课程表单 */
    resetCourseForm() {
      this.courseForm = {
        id: null,
        schoolId: this.schoolId,
        professionId: this.currentProfession ? this.currentProfession.id : null,
        name: '',
        orderNum: 0
      }
      this.isEditingCourse = false
      this.editingCourseId = null
      if (this.$refs.courseForm) {
        this.$refs.courseForm.clearValidate()
      }
    },



    /** 保存新课程 */
    saveCourse() {
      this.$refs.courseForm.validate(valid => {
        if (valid) {
          const courseData = {
            ...this.courseForm,
            schoolId: this.schoolId,
            professionId: this.currentProfession.id,
            orderNum: this.courseForm.orderNum || 0
          }
          
          addClasses(courseData).then(response => {
            this.$message.success("添加课程成功")
            this.resetCourseForm()
            this.getCoursesList()
          }).catch(error => {
            const errorMsg = error?.response?.data?.msg || error?.message || "添加课程失败"
            this.$message.error(errorMsg)
            console.error('添加课程失败:', error)
          })
        }
      })
    },

    /** 编辑课程 */
    editCourse(course) {
      this.courseForm = {
        ...course,
        schoolId: this.schoolId,
        professionId: this.currentProfession.id
      }
      this.isEditingCourse = true
      this.editingCourseId = course.id
    },

    /** 更新课程 */
    updateCourse() {
      this.$refs.courseForm.validate(valid => {
        if (valid) {
          const courseData = {
            ...this.courseForm,
            schoolId: this.schoolId,
            professionId: this.currentProfession.id,
            orderNum: this.courseForm.orderNum || 0
          }
          
          updateClasses(courseData).then(response => {
            this.$message.success("更新课程成功")
            this.resetCourseForm()
            this.getCoursesList()
          }).catch(error => {
            const errorMsg = error?.response?.data?.msg || error?.message || "更新课程失败"
            this.$message.error(errorMsg)
            console.error('更新课程失败:', error)
          })
        }
      })
    },

    /** 删除课程 */
    deleteCourse(course) {
      this.$confirm(`是否确认删除课程"${course.name}"？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delClasses(course.id)
      }).then(() => {
        this.$message.success("删除课程成功")
        this.getCoursesList()
      }).catch((error) => {
        if (error !== 'cancel') {
          const errorMsg = error?.response?.data?.msg || error?.message || "删除课程失败"
          this.$message.error(errorMsg)
          console.error('删除课程失败:', error)
        }
      })
    },

    // ===== 课程编辑相关方法 =====

    /** 打开课程编辑弹出框 */
    openCoursesDialog(profession) {
      console.log('打开课程编辑弹出框，选择的培养计划:', profession)
      console.log('当前院校ID:', this.schoolId)
      
      this.currentProfession = profession
      this.showCoursesDialog = true
      this.resetCourseForm()
      this.getCoursesList()
    },

    /** 关闭课程编辑弹出框 */
    closeCoursesDialog() {
      this.showCoursesDialog = false
      this.currentProfession = null
      this.resetCourseForm()
      this.coursesList = []
    },

    /** 获取课程列表 */
    getCoursesList() {
      if (!this.currentProfession) return
      
      this.coursesLoading = true
      const queryParams = {
        professionId: this.currentProfession.id
      }
      
      console.log('获取课程列表，查询参数:', queryParams)
      
      listClasses(queryParams).then(response => {
        this.coursesLoading = false
        const rawData = response.rows || response.data || []
        console.log('获取到的原始课程数据:', rawData)
        this.coursesList = this.validateAndFixCoursesData(rawData)
        console.log('验证后的课程列表:', this.coursesList)
      }).catch(error => {
        this.coursesLoading = false
        this.coursesList = []
        console.error('获取课程列表失败:', error)
        this.$message.error("获取课程列表失败：" + (error.message || error))
      })
    },

    /** 验证和修复课程数据 */
    validateAndFixCoursesData(data) {
      if (!Array.isArray(data)) return []
      
      return data.filter(item => {
        // 主要根据professionId过滤，确保只显示当前培养计划的课程
        return item.professionId === this.currentProfession.id
      }).map(item => ({
        id: item.id || null,
        schoolId: item.schoolId || this.schoolId,
        professionId: item.professionId || this.currentProfession.id,
        name: item.name || '',
        orderNum: item.orderNum !== null && item.orderNum !== undefined ? Number(item.orderNum) : 999
      })).sort((a, b) => a.orderNum - b.orderNum) // 按 orderNum 升序排列，数值小的在前
    },

    /** 重置课程表单 */
    resetCourseForm() {
      this.courseForm = {
        id: null,
        schoolId: this.schoolId,
        professionId: this.currentProfession ? this.currentProfession.id : null,
        name: '',
        orderNum: 0
      }
      this.isEditingCourse = false
      this.editingCourseId = null
      
      if (this.$refs.courseForm) {
        this.$refs.courseForm.resetFields()
      }
    },

    /** 保存课程 */
    saveCourse() {
      if (!this.currentProfession) {
        this.$message.error('请先选择培养计划')
        return
      }
      
      console.log('准备保存课程，当前培养计划:', this.currentProfession)
      console.log('课程表单数据:', this.courseForm)
      
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          const courseData = {
            ...this.courseForm,
            schoolId: this.schoolId,
            professionId: this.currentProfession.id
          }
          
          console.log('发送到后端的课程数据:', courseData)
          
          addClasses(courseData).then(response => {
            console.log('添加课程成功，后端响应:', response)
            this.$message.success("添加课程成功")
            this.resetCourseForm()
            this.getCoursesList()
          }).catch(error => {
            console.error('添加课程失败:', error)
            this.$message.error("添加课程失败：" + (error.message || error))
          })
        }
      })
    },

    /** 编辑课程 */
    editCourse(course) {
      this.courseForm = {
        id: course.id,
        schoolId: course.schoolId,
        professionId: course.professionId,
        name: course.name,
        orderNum: course.orderNum
      }
      this.isEditingCourse = true
      this.editingCourseId = course.id
    },

    /** 更新课程 */
    updateCourse() {
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          updateClasses(this.courseForm).then(response => {
            this.$message.success("更新课程成功")
            this.resetCourseForm()
            this.getCoursesList()
          }).catch(error => {
            this.$message.error("更新课程失败：" + (error.message || error))
          })
        }
      })
    }
  }
}
</script>
<style scoped>
/* 转校培养计划整体容器 */
.professions-container {
  width: 100%;
  min-height: 600px;
}

/* 左侧内容区域（现在占满全宽） */
.left-content {
  width: 100%;
}

/* 添加按钮容器 */
.add-button-container {
  margin-bottom: 15px;
  text-align: left;
}

/* 全屏抽屉遮罩层 */
.profession-drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  justify-content: flex-end;
  align-items: stretch;
}

/* 右侧抽屉 */
.profession-drawer {
  width: 500px;
  height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  animation: slideInRight 0.3s ease-out;
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

/* 抽屉头部 */
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.drawer-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.close-btn {
  font-size: 18px;
  color: #909399;
  padding: 0;
}

.close-btn:hover {
  color: #409eff;
}

/* 抽屉内容区域 */
.drawer-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

/* 表单样式 */
.profession-form {
  width: 100%;
}

/* 抽屉底部按钮区域 */
.drawer-footer {
  padding: 16px 24px;
  background: #f9fafc;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  flex-shrink: 0;
}

.required-field .el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.required-field .el-form-item__label {
  color: #303133;
  font-weight: 500;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 按钮组样式 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 20px;
}

/* 文本域样式 */
.el-textarea .el-textarea__inner {
  resize: vertical;
  min-height: 80px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profession-drawer {
    width: 100vw;
  }
  
  .drawer-content {
    padding: 16px;
  }
  
  .drawer-footer {
    padding: 12px 16px;
  }
  
  .drawer-header {
    padding: 12px 16px;
  }
}

/* 确保抽屉在最高层级 */
.profession-drawer-overlay {
  z-index: 3000;
}

.profession-drawer {
  z-index: 3001;
}

/* ===== 课程编辑抽屉样式 - 与培养计划抽屉保持一致 ===== */
.courses-drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  z-index: 3010;
  display: flex;
  justify-content: flex-end;
  align-items: stretch;
}

.courses-drawer {
  width: 800px;
  background: white;
  height: 100vh;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  z-index: 3011;
  overflow: hidden;
}

.courses-drawer .drawer-header {
  padding: 20px 24px;
  background: #f9fafc;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.courses-drawer .drawer-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.courses-drawer .close-btn {
  font-size: 18px;
  color: #909399;
  padding: 0;
  border: none;
  background: none;
}

.courses-drawer .close-btn:hover {
  color: #409eff;
}

.courses-drawer .drawer-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.courses-drawer .course-form {
  width: 100%;
}

.courses-drawer .drawer-footer {
  padding: 16px 24px;
  background: #f9fafc;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  flex-shrink: 0;
}

.courses-drawer .required-field .el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.courses-drawer .required-field .el-form-item__label {
  color: #303133;
  font-weight: 500;
}

/* 课程列表表格样式 */
.courses-drawer .courses-list .el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 课程表单项间距 */
.courses-drawer .el-form-item {
  margin-bottom: 20px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 4px;
  flex-wrap: nowrap;
  align-items: center;
}

.operation-buttons .el-button {
  margin: 0;
  padding: 7px 10px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .courses-drawer {
    width: 100vw;
  }
  
  .courses-drawer .drawer-content {
    padding: 16px;
  }
  
  .courses-drawer .drawer-footer {
    padding: 12px 16px;
  }
  
  .courses-drawer .drawer-header {
    padding: 12px 16px;
  }
}
</style>
